/*
 * Copyright © 2018 CODESTD.COM Inc. All rights reserved.
 */
package com.codestd.security.controller;

import com.codestd.security.config.SystemSettings;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录控制器
 *
 * @author jaune
 * @since 1.0.0
 */
@Controller
public class LoginController {

    @Autowired
    private SystemSettings systemSettings;

    /**
     * 跳转到登录页面，如果用户已登录则自动跳转到首页
     */
    @GetMapping("/login")
    public ModelAndView toLoginPage() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            return new ModelAndView("redirect:" + this.systemSettings.getLoginSuccessUrl());
        } else {
            return new ModelAndView("login");
        }
    }

    @PostMapping("/login")
    public void login(HttpServletRequest request, Model model) {
        String errorClassName = (String)request.getAttribute(
                FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        final String ERROR_MESSAGE_ATTR_NAME = "errorMessage";

        if (errorClassName != null) {
            errorClassName = errorClassName.substring(errorClassName.lastIndexOf(".") + 1);
        } else {
            return;
        }
        switch (errorClassName) {
            case "IncorrectCredentialsException":
                model.addAttribute(ERROR_MESSAGE_ATTR_NAME, "密码错误！");
                break;
            case "UnknownAccountException":
                model.addAttribute(ERROR_MESSAGE_ATTR_NAME, "用户名不存在！");
                break;
            case "DisabledAccountException":
                model.addAttribute(ERROR_MESSAGE_ATTR_NAME, "账户已被禁用！");
                break;
            case "LockedAccountException":
                model.addAttribute(ERROR_MESSAGE_ATTR_NAME, "账户已被锁定！");
                break;
            case "CaptchaException":
                model.addAttribute(ERROR_MESSAGE_ATTR_NAME, "验证码输入错误！");
                break;
            default:
                model.addAttribute(ERROR_MESSAGE_ATTR_NAME, "登录失败！");
        }
    }

    /**
     * 注销
     */
    @GetMapping("/logout")
    public void logout() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            SecurityUtils.getSubject().logout();
        }
    }

}
